const loki = require('lokijs')
const fs = require('fs')
// const request = require('superagent');
// var nodeExcel = require('excel-export');
const moment = require('moment')
// 启动log
const log4js = require('log4js');
log4js.configure({
    appenders: {
        cheese: {
            type: 'file',
            filename: './avatarFaile.log'
        }
    },
    categories: {
        default: {
            appenders: ['cheese'],
            level: 'trace'
        }
    }
});
const logger = log4js.getLogger('cheese');

const xls = require('./Untitled-1')

var db = new loki('./SD_DB.db', {
    autoload: true,
    autoloadCallback: databaseInitialize,
    autosave: true,
    autosaveInterval: 4000
});

// implement the autoloadback referenced in loki constructor
function databaseInitialize() {
    var robots = db.getCollection("robots");
    if (robots === null) {
        robots = db.addCollection("robots");
    }
    // kick off any program logic or start listening to external events
    exportLogic(robots);
}


function createRobotDB(robots) {
    var robotJSON = JSON.parse(fs.readFileSync('./SDdata.json'))
    robots.insert(robotJSON)
}

let machineMap = {}
let madchineArr = []

function runProgramLogic(robots) {
    let res = robots.find({})
    // console.log(`已加载${res.length}条数据库内容`)
    // console.log(`已加载${moment(43434)}条数据库内容`)
    let exData = xls.importExl()
    exData = exData.slice(2, )
    exData.forEach(ele => {
        let tmp = robots.findOne({
            'model': ele[4]
        })
        try {
            if (tmp) {
                // tmp.MID = ele[0] || ''
                // tmp.RID = ele[1] || ''
                // tmp.Name = ele[5] || ''
                tmp.get_way = ele[6] || ''
                // tmp.newState = ele[6] || ''
                tmp.rare = ele[8] || ''
                tmp.strength = ele[9] || ''
                tmp.birth_date = ele[7] || ''
                // tmp.Machine = ele[10] && ele[10].toString().split(',') || tmp.Machine
                tmp.MB_sale = ele[11] || ''
                tmp.GB_sale = ele[12] || ''
                tmp.map_sale = ele[13] || ''
                // delete tmp.mergeMap;
                // delete tmp.expTable;
                robots.update(tmp)
            } else {}
        } catch (error) {
            console.log(error)
        }
    });

    // robots.update(res)
    console.log('更新tags完毕')
    db.save()


}

function exportLogic(robots){
    let res = robots.find({})
    xls.mkExl(res)
}

function sorter(a, b, filter) {
    switch (filter) {
        case 'fever':
        case 'rating':
            return Number(b[filter] || 0) - Number(a[filter] || 0)
            break
        case 'birth_date':
            var brith1 = a.birth_date.trim() || '2018-10-10';
            var brith2 = b.birth_date.trim() || '2018-10-10';
            if (moment(brith1).isBefore(brith2)) {
                return 1;
            } else {
                return -1;
            }
            break
    }
}

module.exports = db;